#include "file_handle.h"
#include "QDebug"
#include "QFileDialog"
#include "QFile"
#include "QRegularExpression"
#include "QTextStream"
#include "QStringList"
#include "error_process.h"

FileHandle::FileHandle(QObject *parent)
    : QObject{parent}
{}

void FileHandle::openFile()
{
    this->file_raw_name = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("Files (*.*)"));
    if(file_raw_name.isEmpty())
    {
        qDebug() << "File is empty";
        errorMessage();
    }
}

void FileHandle::myFileProcess()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "", tr("Files (*.*)"));
    if (!fileName.isEmpty()) {
        // 处理文件打开逻辑，例如读取文件内容等
        QFile file(fileName);
        if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
        {
            qDebug() << "Can not open test file" << file.errorString();
            return;
        }

        QTextStream in(&file);
        QTextStream out(&file);
        out.setDevice(&file);

        QString content = in.readAll();
        // qDebug() << "file contect:" << content;

        // QRegularExpression QE(R"(\d+ F BMS [\d\s,-?\d\s\[\]\|]+\n)");           //用来筛选BMS相关信息的正则表达式
        QRegularExpression QE(R"(\d+\s+[A-Z]\s+L\d+\s+S_BMS:\s+\d+\s+\d+,\d+,\d+,\d+)");

        this->list = filterContent(content, QE);

        // saveToFile(file_name, list);
        // qDebug() << "Match content" << list;
        file.close();
    }
}

//处理筛选后的信息，去除无效信息
QStringList FileHandle::filterContent(const QString &content, const QRegularExpression &pattern)
{
    QStringList matches;

    QRegularExpressionMatchIterator i = pattern.globalMatch(content);
    while(i.hasNext())
    {
        QRegularExpressionMatch match = i.next();
        QString matchedText  = match.captured(0);

        static QRegularExpression re("\\n");
        matchedText.remove(re); // 去除换行符
        matches << matchedText;
    }

    return matches;
}

//将筛选出来的信息单独保存成一个文件
void FileHandle::saveToFile()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "", tr("Text Files (*.txt);;Files (*.*)"));
    if(!fileName.isEmpty())
    {
        QFile file(fileName);
        if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            qWarning("Can not open file");
            return;
        }

        QTextStream out(&file);
        for(const QString &item : this->list)
        {
            out << item << "\n";
        }

        this->file_save_name = fileName;
        file.close();
    }
    else
    {
        qWarning("File is not existed\n");
    }

}
